import { defineStore } from 'pinia'

import { useFormStore } from '@/stores/formData.js'
import { decLegend, lineOption, objLegend, options } from '@/composables/SimpleCharts/chartOptions.js'

const formStore = useFormStore()
const { formData } = formStore

export const useSimpleTaskData = defineStore('simpleTaskStore', () => {
  const allTaskData = reactive([])
  const currentIndex = ref(0)

  const PFs = reactive([])
  // 选择的指标值
  const indicator = ref('obj')
  // 算法指标下拉框
  const indicators = ref({})
  // 历史任务记录
  const historyFormData = reactive([])
  // 记录已使用的评估次数
  const evaluations = ref(0)
  const max_fun_eval = ref(0)
  const progress = computed(() => {
    return Math.min(parseFloat((evaluations.value / max_fun_eval.value * 100).toFixed(2)), 100)
  })
  const selectHistoryData = (index) => {
    currentIndex.value = index
  }
  const saveHistory = (algorithm, problem, formData) => {
    // 对象复制
    algorithm = JSON.parse(JSON.stringify(algorithm))
    problem = JSON.parse(JSON.stringify(problem))
    formData = JSON.parse(JSON.stringify(formData))
    historyFormData.push({ algorithm, problem, formData })
  }
  // 拼接表格的option数据
  const getOptionObj = () => {
    let option
    let dim = 0
    // 保存历史信息
    if (indicator.value === 'obj') {
      dim = formData['obj_dim']
      option = options[dim]
      if (option != undefined)
        option.title.text = 'obj'
    } else if (indicator.value === 'dec') {
      dim = formData['var_dim']
      option = options[dim]
      if (option != undefined)
        option.title.text = 'dec'
    } else {
      option = lineOption
    }
    if (dim >= 4) {
      option = options[options.length - 1]
      option.title.text = indicator.value
      option.parallelAxis = dynamicParallelAxis(dim)
    }
    if (indicator.value === 'dec' || indicator.value === 'obj') {
      option.legend = indicator.value === 'dec' ? decLegend : objLegend
      option.series[1].name = indicator.value === 'dec' ? 'PS' : 'PF'
    }
    return JSON.parse(JSON.stringify(option))
  }
  const dynamicParallelAxis = (size) => {
    const temp = []
    for (let i = 0; i < size; i++) {
      temp.push({ dim: i, name: i.toString() })
    }
    return temp
  }
  const simpleTaskInit = (message) => {
    const oneTaskData = {}
    evaluations.value = 0
    max_fun_eval.value = formData['max_fun_eval']
    let temp = getOptionObj()
    PFs.push(message['PF'])
    oneTaskData[indicator.value] = temp
    allTaskData.push(oneTaskData)
    currentIndex.value = allTaskData.length - 1
  }

  const initDataOnError = () => {
    currentIndex.value = 0
    allTaskData.splice(0, allTaskData.length)
    historyFormData.splice(0, historyFormData.length)
    PFs.splice(0, PFs.length)
    evaluations.value = 0
  }

  const simpleTask = (message) => {
    const messageValue = message['indicator_value']
    try {
      if (indicator.value === 'obj' || indicator.value === 'dec') {
        allTaskData[currentIndex.value][indicator.value].series[0].data = messageValue[1]
      } else {
        allTaskData[currentIndex.value][indicator.value].series[0].data.push(messageValue)
        appendIndicateValue(messageValue[1])
      }
      evaluations.value = messageValue[0]
    }catch (e) {
      // do nothing
    }
  }

  // 优化页面渲染
  const handleSimpleTask = (message) => {
    let start = Date.now()
    requestAnimationFrame(() => {
      if (Date.now() - start < 16.6) {
        simpleTask(message)
      } else {
        handleSimpleTask(message)
      }
    })
  }

  const handleSimpleIndicatorTask = (message) => {
    const messageValue = message['indicator_value']
    if (indicator.value !== 'obj' && indicator.value !== 'dec') {
      appendIndicateValue(messageValue[1])
      allTaskData[currentIndex.value][indicator.value].series[0].data.push(messageValue)
    } else {
      allTaskData[currentIndex.value][indicator.value].series[0].data = messageValue
    }
  }
  // 将最后一组数据追加给表格标题 如IGD(xx.xx)
  const appendIndicateValue = (data) => {
    data = data.toExponential(3)
    allTaskData[currentIndex.value][indicator.value].title.text = `${indicator.value}(${data})`
  }

  return {
    initDataOnError,
    allTaskData,
    simpleTaskInit,
    handleSimpleTask,
    currentIndex,
    indicator,
    indicators,
    getOptionObj,
    PFs,
    selectHistoryData,
    saveHistory,
    historyFormData,
    evaluations,
    progress,
    handleSimpleIndicatorTask
  }
})
